<?php
class Memory_model extends CI_Model {
	
	public function add_memory($user_id, $record_id, $times, $interval, $scheduleDate)
	{
		$sql = 'INSERT INTO memory (userId, recordId, times, intervalDays, scheduleDate) VALUES (?, ?, ?, ?, ?)';
		$query = $this->db->query($sql, array($user_id, $record_id, $times, $interval, $scheduleDate));

		return $this->db->affected_rows() > 0;
	}	
	
	public function update_memory($memory_id, $score, $ef)
	{
		$sql = 'UPDATE memory SET handleTime=now(), score=?, ef=? WHERE memoryId=? LIMIT 1';
		$query = $this->db->query($sql, array($score, $ef, $memory_id));

		return $this->db->affected_rows() > 0;
	}
	
	public function review_memory($memory_id, $score)
	{
		$sql = 'UPDATE memory SET score2=? WHERE memoryId=? LIMIT 1';
		$query = $this->db->query($sql, array($score, $memory_id));
		
		return $this->db->affected_rows() > 0;
	}
	
	public function del_memory($record_id)
	{
		$sql = 'DELETE FROM memory WHERE recordId=?';
		$query = $this->db->query($sql, array($record_id));

		return $this->db->affected_rows() > 0; 
	}
	
	public function get_memory_by_id($memory_id)
	{
		$sql = 'SELECT * FROM memory WHERE memoryId=? LIMIT 1';
		$query = $this->db->query($sql, array($memory_id));
		
		return $query->num_rows > 0 ? $query->row() : false;
	}
	
	public function get_schedule_memory($user_id)
	{
		$sql = 'SELECT * FROM memory WHERE userId=? AND scheduleDate<=now() AND score IS NULL'
			.' ORDER BY scheduleDate DESC LIMIT 1';
		$query = $this->db->query($sql, array($user_id));

		return $query->num_rows > 0 ? $query->row() : false;
	}
	
	public function get_review_memory($user_id)
	{
		$sql = 'SELECT * FROM memory WHERE userId=? AND scheduleDate=?'
			.' AND ((score<? AND score2 IS NULL) OR score2<?)'
			.' ORDER BY handleTime LIMIT 1';
		$today = $this->time_utils->get_today();
		$query = $this->db->query($sql, array($user_id, $today, Variable::SCORE_REMEMBER, Variable::SCORE_REMEMBER));
		
		return $query->num_rows > 0 ? $query->row() : false;
	}
	
	public function get_last_memory_handled($record_id)
	{
		$sql = 'SELECT * FROM memory WHERE recordId=? AND score IS NOT NULL ORDER BY scheduleDate DESC LIMIT 1';
		$query = $this->db->query($sql, array($record_id));
		
		return $query->num_rows > 0 ? $query->row() : false;
	}
	
	public function get_last_memory_without_handled($record_id)
	{
		$sql = 'SELECT * FROM memory WHERE recordId=? AND score IS NULL ORDER BY scheduleDate DESC LIMIT 1';
		$query = $this->db->query($sql, array($record_id));
	
		return $query->num_rows > 0 ? $query->row() : false;
	}
}
?>